<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// check if given email exists in tb_users
class register_model extends CI_Model{
	
	
/*
 *****************************BEGIN OF PRIVATE HELPER METHODS*********************************
 * 
 */	
	// validate string variable, cut to its maxlen if needed
	function _validateString ($inputstr, $maxlen=-1){
		$default = '@';   //default str to avoid SQL error
		if (!isset($inputstr)) return $default;   //not assigned str
		if (strlen(trim($inputstr))==0) return $default;   //empty str
		if ($maxlen>0 && strlen(trim($inputstr))>$maxlen){   //str is too long
			return substr(trim($inputstr), 0, $maxlen);
		}
		else{
			return $inputstr;
		}
	}
	
	//generate unique randome validation code
	function _codeGenerator($email){
		$str = '';
		for ($i = 1; $i<=10; $i++) {
		    $str += chr(rand(1, 254));
		}    
		return md5($email . $str);     //return a randome hash code of length 32
	}
	
	//get user data by given conditions
	function _getUserdata($value, $field){
		$SQLStr = "Select * From tb_user  Where " . $field . "  =  ? ";
		$query = $this->db->query($SQLStr, $value);
		if ($query->num_rows()>0){
			return  $query->row();
		}
		else{
			return null;
		}	
	}
/*
***************************** END OF PRIVATE HELPER METHODS*********************************
 */
	
	//get user data by email
	function getUserdataByEmail($email){
        return $this ->_getUserdata($email, 'email');
		
	}
	
	//get user data by username
	function getUserdataByUsername($username){
        return $this ->_getUserdata($username, 'user_name');
	}
	
	//get user data by activation code
	function getUserdataByCode($code){
        return $this ->_getUserdata($code, 'validationCode');
	}

	//get user data by id
	function getUserdataById($id){
		return $this ->_getUserdata($id, 'id');
	}
	
	//get account status
	function getUserStatById($id){
		$row = $this ->_getUserdata($id, 'id');
		if (!isset($row)){
			return STAT_ERROR;
		}
		else {
			return $row -> account_stat;
		}
	}
	
	//check if vaidation code valid
	function isCodeValid($Code){
		if (!isset($Code)){  //missing parameter
			return false;
		}
		else {
			$sessionCode = $this->session->userdata('validationCode');   //get code from session
			return $sessionCode==$Code;    //code is valid
		}
	}
	
	
	// if given email address exists in database then return true, otherwise return false
	function checkEmail($EmailAddress){
        $_EmailAddress = $this -> _validateString($EmailAddress);   //validation

        $q = $this->db->query('select count(*) as e from tb_user where email = ?', $_EmailAddress);   //create a SQL query
		if ($q->num_rows()>0) {  //only read data when table is not empty			
			if ( $q->row()->e >0)    
				return 'true';
			else
				return 'false';
		}
		else {
			return 'false';
		}
	}
	
	//check if given username exists in database
	function checkUserName($UserName){
		$_UserName = $this -> _validateString($UserName);   //check validation

		$q = $this->db->query('Select count(*) as u from tb_user where user_name = ?', $_UserName);   //create a SQL query
		if ($q->num_rows()>0) {  //has records
            if ($q -> row()->u >0 )
			   return 'true';
            else
            	return 'false';
		}
		else {
			return 'false';
		}
	}
	
	//set email session as current time
	function setEmailSession($Email){
		$sessiondata = array($Email => time() );
		$this ->session -> set_userdata($sessiondata);		
	}
	
	//only allow resent email every 10 minutes
	function resendIntervalCheck($Email) {
		$PrevSendingTime =$this ->session ->userdata($Email);    //read previous sending time
		
		if ($PrevSendingTime=='') {  //first time to resend out emails
			$this -> setEmailSession($Email);   //save current time to session
			return TRUE;
		}
		else {
			$interval = time() - $PrevSendingTime;    //get interval by sec
			if ($interval >= MIN_INTERVAL){        //minume resending email time interval is 10 minuts, 600 secs.  
			    $this -> setEmailSession($Email);   //save current time to session
				return TRUE;
			}
			else {
				return FALSE;
			}
		}
	}

	
	function exchangeEmail($oldEmail, $newEmail){
		$data = array('email' => $newEmail);
		$where = "email = '" . $oldEmail . "'"; 
		
		$SQLStr = $this->db->update_string('tb_user', $data, $where);		
		$this -> db -> query($SQLStr);              //Run SQL to exchange email
		
		return $this ->checkEmail($newEmail) == 'true';   //check if successfully exchanged
	}
   
  // active user's account if code is valide
  function activeUserAccount($code){
      $vcode = trim($code);   //take away white spaces 
  	  if (strlen($vcode)<=0){
  	  	 return 'invalidcode';
  	  }
  	  $row = $this -> getUserdataByCode($vcode);   //read out user data from database
  	  if (isset($row)){   //user located
  	  	    $stat = $row ->account_stat;   //user account's status
         	$id = $row -> id;   //get user's id
            if ($stat == STAT_ACTIVED) {   //user account already actived
            	return 'active';
            }
            elseif ($stat == STAT_DISABLED) {  //user account disabled
            	return 'disable';
            }
            //-------------------- start to update user's account status ---------------
            $SQL = "Update tb_user Set account_stat= ? Where id=?";
            $this -> db -> query($SQL, array(STAT_ACTIVED, $id));    //update user's status
            
            $newStat = $this->getUserStatById($id);    //verifty new account status
            if (!isset($newStat)){
            	return 'error';   //not be able to read status from databse
            }
            else{
            	if( $newStat == STAT_ACTIVED) 
            		return 'success';
            	else
            		return 'fail';
            }
  	  }
  	  else{  //cannot locate user
  	  	   return 'nouser' ;
  	  }
  }	
	
   // resent validation email to given email address
   function resendValidationEmail($Email){
   	   $row = $this->getUserdataByEmail($Email);   //get a row of user data
   	   if (isset($row)){  //user located
   	   	  $Username = $row -> user_name;
   	   	  $Code = $row -> validationCode;
   	   	  $Stat = $row -> account_stat;
   	   	   
   	   	  if ($Stat == STAT_ACTIVED) {    //user already activated
   	   	  	return 'approved';
   	   	  }
   	   	  return  $this -> register_model ->sendValidationEmail($Email, $Username, $Code, FALSE);  //resend validation email
   	   }	  
   	   else {
   	   	  	return  'invalidemail';     //cannot locate email in database
   	   	}
   }
	
	//send out validation email
	function sendValidationEmail($Email, $Username, $Code, $ignoreTime=TRUE){
		if (strlen(trim($Email))==0) {    //parameters check
			return 'invalid email address';
     	    exit;
		}
		elseif (strlen(trim($Username))==0) {
			return 'invalid user name';
     	    exit;
		}
		elseif (strlen(trim($Code))==0) {
			return 'invalid activation code';
     	    exit;
		}
		
		if (!$ignoreTime){    //need to check email sending intervals
			if (!$this -> resendIntervalCheck($Email)){
				return 'again';
				exit;
			}
		}
		
		
		$this -> load -> library('phpmailer');
		$mail = $this -> phpmailer;
		
		$mail->IsSMTP();                         // SMTP mail
		$mail->CharSet = 'UTF-8';         //中文邮件
		$mail->SMTPAuth = true;            //开启SMTP认证
		$mail->SMTPSecure = $this->config -> item('smtp_secur');          // sets the prefix to the servier, ssl or tls
		$mail->Host       =  $this ->config -> item('smtp_server');            // sets SMTP server parameters
		$mail->Port       = $this->config->item('port');                   
		$mail->Username = $this->config->item('username');
		$mail->Password = $this->config->item('password');
		$mail->From = $this->config->item('email_from');   //sender
		$mail->FromName = $this->config->item('email_from_name');  

		$mail->AddAddress($Email, $Username); //添加收件人
		$mail->AddReplyTo("do-not-reply@gmail.com", "Do not reply");    //回复地址
		$mail->WordWrap = 60;                    //设置每行字符长度

		$mail->IsHTML(true);                 // 是否HTML格式邮件
		$mail->Subject = "激活您的Qiqu taobao帐号";          //邮件主题

		$activationURL = $this->config->item('base_url') . 'register/activation?code=' . $Code;
		$content   = '<div id=":12x">';
        $content .='<h1 style="text-align:center">激活邮件</h1>';
		$content .= '<ul style="list-style-type:none">';
		$content .= '	<li>亲爱的<span style="color:#900">' . $Username . '</span>，您好</li>';
		$content .= '	<li>';
		$content .= '您已注册为<a href="http://www.qiqutaobao.com" target="_blank">Qiqu taobao</a>的会员，';
		$content .= '请点击此处 <a href="' . $activationURL . '" target="_blank">激活</a>您的帐户。';
		$content .= '</li>';
		$content .= '<li>如果上述链接不能使用，请将下面的链接复制到浏览器地址栏：</li>';
		$content .= '<li style="color:green"><a href="' . $activationURL . '" target="_blank">' . $activationURL . '</a></li><li></li>';
		$content .= '	<li>您的注册信息为：</li><li>帐号：<span style="color:red">' . $Username . '</span></li>';
		$content .=  '<li>邮件地址：<span style="color:red"><a href="mailto:' . $Email . ' " target="_blank">' . $Email . '</a></span> </li>';
		$content .= '<li>您可以使用账号或邮件登录网站</li><li>激活邮件有效期为24小时，请在24小时内激活，谢谢。</li>';
		$content .= '<li>--------------------------------------------------------------------------</li>';
		$content .= '<li>此邮件是由Qiqu taobao网系统发出，系统不接收回复邮件，请勿直接回复。</li>';
		$content .= '<li>足不出户，买遍淘宝！ <a href="http://www.qiqutaobao.com" target="_blank">http://www.qiqutaobao.com</a></li>';
		$content .= '</div>';		
				
		$non_htmlcontent  = '激活邮件\n\n';
        $non_htmlcontent  .= '亲爱的'. $Username . '，您好\n';
        $non_htmlcontent  .= '您已注册为www.qiqutaobao.com的会员，请将下面的链接复制到浏览器地址栏：\n' .  $activationURL . '\n';
        $non_htmlcontent  .= '您的注册信息为：\n';
        $non_htmlcontent  .= '帐号：'. $Username .'\n';
        $non_htmlcontent  .= '邮件地址：'. $Email . '\n';
        $non_htmlcontent  .= '您可以使用账号或邮件登录网站\n';
        $non_htmlcontent  .= '激活邮件有效期为24小时，请在24小时内激活，谢谢。\n';
        $non_htmlcontent  .= '--------------------------------------------------------------------------\n';
        $non_htmlcontent  .= '此邮件是由Qiqu taobao网系统发出，系统不接收回复邮件，请勿直接回复。\n';
        $non_htmlcontent  .= '足不出户，买淘宝！ http://qiqutaobao.com';				
		$mail->Body    = $content;                //邮件内容
		$mail->AltBody = $non_htmlcontent;  //邮件正文不支持HTML的备用显示
		

		if(!$mail->Send()){
			return $mail->ErrorInfo;
     	    exit;
		}
		else {
		   return 'success';
     	   exit;
		}
	}
	
	//insert a new user
	function insertNewUser($email, $username,$password, $telphone, $address){
		$_email = strtolower( $this -> _validateString($email,100));    //validate all input parameters
       $_username = strtolower($this -> _validateString($username, 20));
       $_password = $this -> _validateString ($password, 20);
       $_telphone = $this -> _validateString ($telphone, 20);
       $_address = $this -> _validateString ($address, 255);
        
       $usertype = 0;        //normal user
       $accountstat = STAT_PEDING;   //non-activated
       $validationcode = $this -> _codeGenerator($_email);    //generate validation code
       
       $values = array(    //prepare insert values
       		'email' => $_email,
       		'user_name' => $_username,
       		'password' => md5($_password),
       		'phone1' => $_telphone,
       		'address' =>$_address,
       		'user_type' => $usertype,
       		'account_stat' => $accountstat,
       		'validationCode' => $validationcode,
       		);
      
       $SQLStr = $this ->db -> insert_string('tb_user', $values);    //build a insert into SQL
       $this ->db-> query($SQLStr);   //insert data 
       $newid = $this ->db -> insert_id();    //get the id of insert data
       if (!isset($newid)){    //failed to insert new data
       	   return false;
       }
       else {      	  
       	  $SQLStr = 'Update tb_user Set validationTime = now() Where id= ' . $newid;    //update validation time 
       	  $this -> db -> query($SQLStr);
       	  
       	  $this -> sendValidationEmail($_email, $_username, $validationcode);
       	  return true;
       }
	}

	//--------------------------- forgot password functions ----------------------------------
	
	//check if username & email available
   function username_emailCheck($Username, $Email){
   	  if (strlen(trim($Email))==0) {    //parameters check
   		  return 'Invalid email address';
   	  }
   	  elseif (strlen(trim($Username))==0) {
   		  return 'Invalid user name';
   	  }
   	
   	  $row = $this ->getUserdataByEmail($Email);  
   	  if (!isset($row)){  //cannot locate user by email
   		  return 'No such username or email exists in database.';
   	  }
   	  else{
   		  if ($row-> user_name == $Username  && $row-> email == $Email){   		    
   			  return $this ->sendResetPwdEmail($row->email, $row->user_name, $row->validationCode);   //send out password reset email
   		  }
   		  else {
   			  return 'User name does not match email address.';
   		}
   	  }	
   }
	
	
	// send out email and links to reset password
	function sendResetPwdEmail($Email, $Username, $Code, $ignoreTime=TRUE){
		if (strlen(trim($Email))==0) {    //parameters check
			return 'invalid email address';
		}
		elseif (strlen(trim($Username))==0) {
			return 'invalid user name';
		}
		elseif (strlen(trim($Code))==0) {
			return 'invalid activation code';
		}
		
		if (!$ignoreTime){    //need to check email sending intervals
			if (!$this -> resendIntervalCheck($Email . '_resetpassword')){
				return 'again';
			}
		}
		
		$this -> load -> library('phpmailer');
		$mail = $this -> phpmailer;
		
		$mail->IsSMTP();                      // SMTP mail
		$mail->CharSet = 'UTF-8';         //中文邮件
		$mail->SMTPAuth = true;          //开启SMTP认证
		$mail->SMTPSecure = $this->config -> item('smtp_secur');          // sets the prefix to the servier, ssl or tls
		$mail->Host       =  $this ->config -> item('smtp_server');            // sets SMTP server parameters
		$mail->Port       = $this->config->item('port');
		$mail->Username = $this->config->item('username');
		$mail->Password = $this->config->item('password');
		$mail->From = $this->config->item('email_from');   //sender
		$mail->FromName = $this->config->item('email_from_name');
		
		$mail->AddAddress($Email, $Username); //添加收件人
		$mail->AddReplyTo("do-not-reply@gmail.com", "Do not reply");    //回复地址
		$mail->WordWrap = 60;                    //设置每行字符长度
		
		$mail->IsHTML(true);                 // 是否HTML格式邮件
		$mail->Subject = "找回你的Qiqu taobao帐号密码";          //邮件主题
		
		$activationURL = LOGIN_PAGE()  . '/resetpassword?code=' . $Code;   //Reset password URL

		$content  = '<div id=":yo" class="ii gt adP adO"><div id=":yn">';
		$content .='<h1 style="text-align:center">找回密码</h1>';
		$content .='<ul style="list-style-type:none"><div class="im">';
		$content .='<li>亲爱的<span style="color:#900">'. $Username .'</span>，您好</li><li>&nbsp;</li>';
		$content .='<li>您忘记了密码吗？不要着急哦！请您';	
		$content .='<a href="' . $activationURL . '" target="_blank">点击这里</a>重新设置密码！该链接24小时内有效。';
		$content .='</li>';
		$content .='<li>如果您不能点击，请将以下链接复制到浏览器地址栏中访问，<wbr>也可以重新设置密码！</li>';
		$content .='</div><li><a href="' . $activationURL .'" target="_blank">' . $activationURL .'</a></li>';
		$content .='<div class="im"><li>&nbsp;</li>';
		$content .='<li>--------------------------------------------------------------------------</li>';
		$content .='<li>此邮件是由Qiqu taobaoi网系统发出，系统不接收回复邮件，请勿直接回复。</li>';
		$content .='<li>足不出户，买遍淘宝！ <a href="http://www.qiqutaobao.com" target="_blank">http://www.qiqutaobao.com</a> </li>';
		$content .='</div>';
		$content .='</ul></div></div>';		

				
		$non_htmlcontent  = '找回密码\n\n';
		$non_htmlcontent  .= '亲爱的'. $Username . '，您好\n';
		$non_htmlcontent  .= '您忘记了密码吗？不要着急哦！请将以下链接复制到浏览器地址栏中访问，也可以重新设置密码！\n' .  $activationURL . '\n';
		$non_htmlcontent  .= '此邮件有效期为24小时，请在24小时内重设密码，谢谢。\n';
		$non_htmlcontent  .= '--------------------------------------------------------------------------\n';
		$non_htmlcontent  .= '此邮件是由Qiqu taobaoi网系统发出，系统不接收回复邮件，请勿直接回复。。\n';
		$non_htmlcontent  .= '足不出户，买遍淘宝！ http://qiqutaobao.com';
		$mail->Body    = $content;                //邮件内容
		$mail->AltBody = $non_htmlcontent;  //邮件正文不支持HTML的备用显示
		
		
		if(!$mail->Send()){
			return $mail->ErrorInfo;
		}
		else {
			return 'success';
		}
}


//reset password
function resetPassword($code){
	if (strlen(trim($code))<=0){
		return array("Invalid code.","");
	}
	
	$row = $this-> getUserdataByCode($code);   //get data
	if (!isset($row)){   //cannot locate user in database
		return array("Cannot locate user in database.", "");
	}
	else{
		$id = $row->id;
        $newCode = $this->_codeGenerator($row->email);   //generate a new code
        
        $SQLStr ='Update tb_user Set  validationCode = ? where id = ?';
        $this ->db -> query($SQLStr, array($newCode, $id));   //update validation code          
        return array('success', $id);    //first item is error message, 2nd element is user id   
	}
}

//检查登录是否合法
function verifyLogin($username, $password){
	if (!IsValidEmail($username)){   //user name login
		$userdata = $this ->getUserdataByUsername($username);
	}
	else{   //user email login
		$userdata = $this ->getUserdataByEmail($username);
	}
	
    
	if (!isset($userdata)){   //cannot locate user
		return array(false, "邮箱, 用户名或密码输入错误, 请重新输入");
	}
	else{
		if (md5($password) == $userdata->password){    //password is ok
		    if ($userdata -> account_stat ==STAT_PEDING)
		    	return array(false, "用户名还没有激活. 请检查系统发送的激活邮件.");
		    elseif ($userdata -> account_stat ==STAT_DISABLED)	 
		        return array(false, "用户名已经被停用, 请与站长联系.");
		    else {
		        return array(true, "");	
		    }
		}    
		else {
			return array(false, "邮箱, 用户名对应的密码输入错误, 请重新输入");
		}
		
	}
	
}
	
	
}